package com.lean.android.ad

import android.view.ViewGroup
import android.widget.FrameLayout
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.CompositionLocalProvider
import androidx.compose.runtime.DisposableEffect
import androidx.compose.runtime.rememberCoroutineScope
import androidx.compose.ui.Modifier
import androidx.compose.ui.viewinterop.AndroidView
import com.lean.android.ad.core.AdLoaders
import com.lean.android.ad.utils.DisplayHelper
import com.lean.android.localprovider.LocalActivity
import kotlinx.coroutines.launch

@Composable
fun FeedAd(key: String) {
    CompositionLocalProvider(LocalFeedAdProvider provides FeedAdProviderCache.getProvider(key)) {
        FeedAdView()
    }
}

@Composable
private fun FeedAdView(
    modifier: Modifier = Modifier, feedAdProvider: FeedAdProvider = LocalFeedAdProvider.current
) {
    val scope = rememberCoroutineScope()
    val activity = LocalActivity.current

    DisposableEffect(key1 = feedAdProvider) {
        scope.launch {
            feedAdProvider.requestFeedAd(activity)
        }
        onDispose {
            feedAdProvider.cachedFeedAd()
        }
    }

    when (val feedAdState = feedAdProvider.feedAdState) {
        is FeedAdState.Loading -> {
            Text(text = "ad is loading")
        }

        is FeedAdState.Closed -> {
            Text(text = "ad is closed")
        }

        is FeedAdState.Cached -> {
            AndroidView(modifier = modifier, factory = { context ->
                FrameLayout(context)
            }, update = { adContainer ->
                val ad = feedAdState.ad
                val adView = ad.adView ?: return@AndroidView
                val adLayoutParams = ViewGroup.LayoutParams(
                    ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT
                )
                DisplayHelper.removeFromParent(adView)
                adContainer.removeAllViews()
                adContainer.addView(adView, adLayoutParams)
            })
        }

        is FeedAdState.Loaded -> {
            AndroidView(modifier = modifier, factory = { context ->
                FrameLayout(context)
            }, update = { adContainer ->
                val ad = feedAdState.ad
                AdLoaders.renderFeedAd(activity, adContainer, ad, onAdFinished = {
                    feedAdProvider.closeFeedAd()
                })

            })
        }

        is FeedAdState.Error -> {
            Text(text = "ad error code ${feedAdState.code}, message ${feedAdState.message}")
        }
    }
}



